package com.sugar.subscribe.course.module.business.service.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.sugar.subscribe.course.module.business.controller.app.config.vo.AppBasicConfigRespVO;
import com.sugar.subscribe.course.module.business.enums.config.BizConfigEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import com.sugar.subscribe.course.module.business.controller.admin.config.vo.*;
import com.sugar.subscribe.course.module.business.dal.dataobject.config.BizConfigDO;
import com.sugar.subscribe.course.framework.common.pojo.PageResult;
import com.sugar.subscribe.course.framework.common.util.object.BeanUtils;

import com.sugar.subscribe.course.module.business.dal.mysql.config.BizConfigMapper;

import static com.sugar.subscribe.course.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.subscribe.course.module.business.enums.ErrorCodeConstants.BIZ_CONFIG_NOT_EXISTS;
import static com.sugar.subscribe.course.module.business.enums.config.BizConfigEnum.*;

/**
 * 参数配置 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class BizConfigServiceImpl implements BizConfigService {

    @Resource
    private BizConfigMapper bizConfigMapper;

    @Override
    public Long createConfig(BizConfigSaveReqVO createReqVO) {
        // 插入
        BizConfigDO config = BeanUtils.toBean(createReqVO, BizConfigDO.class);
        bizConfigMapper.insert(config);

        // 返回
        return config.getId();
    }

    @Override
    public void updateConfig(BizConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateConfigExists(updateReqVO.getId());
        // 更新
        BizConfigDO updateObj = BeanUtils.toBean(updateReqVO, BizConfigDO.class);
        bizConfigMapper.updateById(updateObj);
    }

    @Override
    public void deleteConfig(Long id) {
        // 校验存在
        validateConfigExists(id);
        // 删除
        bizConfigMapper.deleteById(id);
    }

    @Override
        public void deleteConfigListByIds(List<Long> ids) {
        // 删除
        bizConfigMapper.deleteByIds(ids);
        }


    private void validateConfigExists(Long id) {
        if (bizConfigMapper.selectById(id) == null) {
            throw exception(BIZ_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public BizConfigDO getConfig(Long id) {
        return bizConfigMapper.selectById(id);
    }

    @Override
    public PageResult<BizConfigDO> getConfigPage(BizConfigPageReqVO pageReqVO) {
        return bizConfigMapper.selectPage(pageReqVO);
    }

    // ======================================== 其它 接口 ========================================

    @Override
    public <T> T getBizConfigByKey(BizConfigEnum configEnum, Class<T> cls) {
        BizConfigDO config = bizConfigMapper.selectOne(BizConfigDO::getConfigKey, configEnum.getValue());
        if (Objects.isNull(config))
            throw exception(BIZ_CONFIG_NOT_EXISTS);

        return Convert.convert(cls, config.getValue());
    }

    @Override
    public <K, T> Map<K, T> getBizConfigMapByKeys(Class<K> kCls, Class<T> cls, BizConfigEnum... configEnums) {
        List<BizConfigDO> bizConfigs = bizConfigMapper.selectList(Wrappers.<BizConfigDO>lambdaQuery()
                .in(BizConfigDO::getConfigKey, Arrays.stream(configEnums).map(BizConfigEnum::getValue).collect(Collectors.toList())));
        return bizConfigs
                .stream()
                .collect(Collectors
                        .groupingBy(o -> kCls.equals(BizConfigEnum.class) ? kCls.cast(BizConfigEnum.find(o.getConfigKey())) : kCls.cast(o.getConfigKey()),
                                Collectors.mapping(BizConfigDO::getValue,
                                        Collectors.collectingAndThen(Collectors.toList(),
                                                list -> list.isEmpty() ? null : Convert.convert(cls, list.get(0))))));
    }

    // ======================================== APP 接口 ========================================

    @Override
    public AppBasicConfigRespVO appGetBizConfigBasic() {
        Map<BizConfigEnum, String> configMap = this.getBizConfigMapByKeys(BizConfigEnum.class, String.class,
                USER_AGREEMENT,
                PRIVACY_POLICY,
                HOME_BANNER,
                ABOUT_US,
                SERVICE_MOBILE,
                PROJECT_LOGO,
                PROJECT_NAME);

        AppBasicConfigRespVO respVO = new AppBasicConfigRespVO();

        respVO.setUserAgreement(configMap.get(USER_AGREEMENT));
        respVO.setPrivacyPolicy(configMap.get(PRIVACY_POLICY));
        respVO.setAboutUs(configMap.get(ABOUT_US));
        respVO.setServiceMobile(configMap.get(SERVICE_MOBILE));
        respVO.setProjectLogo(configMap.get(PROJECT_LOGO));
        respVO.setProjectName(configMap.get(PROJECT_NAME));
        String bannerStr = configMap.get(HOME_BANNER);
        if (StrUtil.isBlank(bannerStr))
            respVO.setHomeBanners(new String[]{});
        else
            respVO.setHomeBanners(bannerStr.split(","));

        return respVO;
    }
}